<template>
  <div>
    <div class="top">
      <div id="components-form-demo-advanced-search">
        <a-row :gutter="24" style="margin-bottom: 15px">
          <a-col :span="6">
            产品名称：
            <a-input :maxLength="128" v-model="searchData.chineseName" />
          </a-col>
          <a-col :span="6"> SKU：<a-input :maxLength="128" v-model="searchData.sku" /> </a-col>
          <a-col :span="6">
            产品标签：<a-input :maxLength="128" v-model="searchData.productTag" />
          </a-col>
          <a-col :span="6" v-show="expand">
            产品分类：
            <a-select
              default-value="全部"
              style="width: 60%"
              v-model="searchData.platformClassify"
              allowClear
            >
              <a-select-option
                v-for="item in platformOptions"
                :key="item.key"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-col>

          <a-col :span="6">
            <div v-show="!expand">
              <span
                style="margin-right: 20px"
                @click="isSearch = !isSearch"
                v-show="isSmall"
              >
                更多
                <a-icon v-show="isSearch == true" type="down" />
                <a-icon v-show="isSearch == false" type="up" />
              </span>
              <span>
                <a-button type="primary" class="top-btn" @click="isOnFile">
                  已归档查询
                </a-button>
              </span>
              <span style="margin-left: 20px">
                <a-button type="primary" class="top-btn" @click="searchBtn">
                  查询
                </a-button>
                <a-button
                  type="primary"
                  class="top-btn"
                  style="margin-left: 10px"
                  @click="resetBtn"
                >
                  重置
                </a-button>
              </span>
              <a
                :style="{ marginRight: '8px', fontSize: '14px' }"
                @click="expand = !expand"
              >
                {{ expand ? "折叠" : "展开" }}
                <a-icon :type="expand ? 'up' : 'down'" />
              </a>
            </div>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-show="expand">
          <!-- <a-col :span="6">
            <div v-show="expand">
              自有分类：
              <a-select
                allowClear
                default-value="全部"
                style="width: 60%"
                v-model="searchData.selfClassify"
                >·
                <a-select-option
                  v-for="item in freedomOptions"
                  :key="item.key"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </div>
          </a-col> -->
          <a-col :span="6">
            <div v-show="expand">
              创建时间：
              <a-range-picker
                style="width: 60%"
                :placeholder="['年/月/日', '年/月/日']"
                format="YYYY-MM-DD"
                v-model="dateTime"
                @change="DateChange"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div v-show="expand">
              <span
                style="margin-right: 20px"
                @click="isSearch = !isSearch"
                v-show="isSmall"
              >
                更多
                <a-icon v-show="isSearch == true" type="down" />
                <a-icon v-show="isSearch == false" type="up" />
              </span>
              <span>
                <a-button type="primary" class="top-btn" @click="isOnFile">
                  已归档查询
                </a-button>
              </span>
              <span style="margin-left: 10px">
                <a-button type="primary" class="top-btn" @click="searchBtn">
                  查询
                </a-button>
                <a-button
                  type="primary"
                  class="top-btn"
                  style="margin-left: 10px"
                  @click="resetBtn"
                >
                  重置
                </a-button>
              </span>
              <a
                :style="{
                  marginRight: '8px',
                  fontSize: '14px',
                  marginLeft: '10px',
                }"
                @click="expand = !expand"
              >
                {{ expand ? "折叠" : "展开" }}
                <a-icon :type="expand ? 'up' : 'down'" />
              </a>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>
    <div class="add" style="margin: 10px 0">
      <span>
        <a-button
          type="primary"
          style="background: #409cff; color: #ffff; border: none"
          @click="addNewSKU"
        >
          新建SKU
        </a-button>
      </span>
      <span style="margin-left: 20px">
        <a-button
          @click="SkuIncShowModel"
          type="primary"
          style="background: #409cff; color: #ffff; border: none"
        >
          批量导入SKU
        </a-button>
      </span>
      <span style="margin-left: 20px">
        <a-dropdown style="background: #409cff; color: #ffff; border: none">
          <a-menu slot="overlay" @click="handleMenuClick">
            <a-menu-item key="0"> g;cm*cm*cm </a-menu-item>
            <a-menu-item key="1"> lb;in*in*in </a-menu-item>
            <!-- <a-menu-item key="2"> oz;ft*ft*ft </a-menu-item> -->
          </a-menu>
          <a-button style="margin-left: 8px">
            单位转换 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </span>
      <span>
        <a
          href="./Skumodel.xlsx"
          target="_blank"
          style="
            margin-left: 40px;
            border-bottom: 1px solid #2929e0;
            color: #2929e0;
          "
          >下载批量导入模板</a
        >
      </span>
    </div>
    <div style="margin-top: 15px">
      <span style="margin-right: 20px">
        <a-button type="primary" class="top-btn" @click="batchIsOnFile">
          批量归档SKU
        </a-button>
      </span>
      <span style="margin-right: 20px">
        <a-button type="primary" @click="showConfirm" class="top-btn">
          批量删除SKU
        </a-button>
      </span>
    </div>
    <!-- //表格 -->
    <a-spin tip="Loading..." :spinning="spinning">
      <a-table
        :scroll="{ x: 1500 }"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
        :columns="columns"
        :data-source="tabledata"
        :pagination="false"
      >
        <span slot="weightUnit" slot-scope="text, record">
          {{
            record.weight +
            (record.unitWeight == 0
              ? "g"
              : record.unitWeight == 1
              ? "lb"
              : "oz")
          }}
        </span>
        <span slot="action" class="action" slot-scope="text, record">
          <a
            slot="action"
            href="javascript:;"
            v-if="record.isOnFile == 0"
            @click="(e) => eidtRow(e, record, 'edit')"
            >编辑</a
          >
          <a
            slot="action"
            href="javascript:;"
            v-if="record.isOnFile == 1"
            @click="(e) => eidtRow(e, record, 'info')"
            >详情</a
          >
          <a-divider type="vertical" v-if="record.isOnFile == 0" />
          <a-dropdown :trigger="['click']" v-if="record.isOnFile == 0">
            <a class="ant-dropdown-link"> 标签下载 </a>
            <a-menu
              slot="overlay"
              @click="(e) => eidtRow(e, record, 'download')"
              style="text-align: center"
            >
              <a-menu-item key="0"> 60*30mm </a-menu-item>
              <a-menu-item key="1"> 自定义打印 </a-menu-item>
              <a-menu-item key="3"> letter </a-menu-item>
              <a-menu-item key="4"> A4 </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </a-spin>
    <!-- 分页器 -->
    <div style="margin: 20px 0; text-align: center">
      <a-config-provider :locale="locale">
        <a-pagination
          show-size-changer
          :pageSizeOptions="['10', '20', '30']"
          :show-total="
            (total) => `${$t('m.page.Total')} ${total} ${$t('m.page.items')}`
          "
          @showSizeChange="showChange"
          :buildOptionText="
            (props) => ` ${props.value} ${$t('m.page.a')}/${$t('m.page.page')}`
          "
          show-quick-jumper
          :current="searchData.current"
          :total="searchData.total"
          @change="onChangePage"
        />
      </a-config-provider>
    </div>
    <!-- //弹出框 -->
    <SKUListModel
      :platformOptions="platformOptions"
      :freedomOptions="freedomOptions"
      :getTableData="getTableData"
    />
    <!-- 批量导入模态框 -->
    <SkuInc :getTableData="getTableData" />
    <!-- 打印 -->
    <TagsModal />
    <!-- <img ref="barcode" id="pdfDom" :src="captchaImg" @click="getPdf()" /> -->
  </div>
</template>

<script>
import TagsModal from "@/components/clientSide/SKUManage/SKUList/TagsModal.vue";
import SKUListModel from "@/components/clientSide/SKUManage/SKUList/SKUListModel.vue";
import SkuInc from "@/components/clientSide/SKUManage/SKUList/SkuInc.vue";
import req from "@/utils/req";
import {
  SKU_TypeTree,
  SKU_TableList,
  SKU_batchDelete,
  SKU_batchIsOnFile,
  SKU_PDF6030,
  SKU_PDFA4,
} from "@/apis/clientSide/SKUManage/SKUList";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
import moment from "moment";
export default {
  components: {
    SKUListModel,
    SkuInc,
    TagsModal,
  },
  watch: {
    windowWidth(val) {
      let that = this;

      if (val < 1366) {
        that.isSmall = true;
      } else {
        that.isSmall = false;
      }
    },
  },
  created() {
    if (this.windowWidth <= 1366) {
      this.isSmall = true;
    }
    // 获取分类
    this.getBatchSKUTypeTree();
    //获取表格数据
    this.getTableData();
  },
  mounted() {
    var that = this;
    // <!--把window.onresize事件挂在到mounted函数上-->
    window.onresize = () => {
      return (() => {
        window.fullHeight = document.documentElement.clientHeight;
        window.fullWidth = document.documentElement.clientWidth;
        that.windowHeight = window.fullHeight; // 高
        that.windowWidth = window.fullWidth; // 宽
      })();
    };
  },
  data() {
    return {
      spinning: false,
      expand: false,
      dateTime: [],
      isSmall: false,
      smallScreen: {
        width: "66%",
        display: "flex",
        flexWrap: "wrap",
      },
      topSearch: {
        display: "flex",
      },
      windowWidth: document.documentElement.clientWidth, //实时屏幕宽度
      windowHeight: document.documentElement.clientHeight, //实时屏幕高度
      isSearch: false,
      htmlTitle: "条形码",
      captchaImg: "",
      startTime: null,
      endTime: null,
      //单位标杆
      units: "重量",
      unitsSize: "长(cm)*宽(cm)*高(cm)",
      unitFlag: "重量(g)",
      locale,

      //平台分类树1
      platformOptions: [],
      platformArray: [],
      //自有分类树2
      freedomOptions: [],
      freedomArray: [],
      //表格数据
      tabledata: [],
      //表格选中提交后台数组
      tablecheckedArray: [],
      //表格checked数组
      selectedRowKeys: [], // Check here to configure the default column
      //搜索框数据
      searchData: {
        total: 0,
        size: 10,
        current: 1,
        chineseName: "",
        productTag: "",
        startWeight: "",
        endWeight: "",
        boxSize: "**",
        selfClassify: "",
        startTime: "",
        endTime: "",
        sku: "",
        width: "",
        height: "",
        long: "",
        isOnFile: 0,
        unitSystem: "0",
        platformClassify: "",
      },
      unitsFlag: "0",
      //分页数据
    };
  },
  methods: {
    disabledDate(current) {
      return (
        current && current < moment(this.searchData.startTime).endOf("day")
      );
    },
    //重置按钮
    resetBtn() {
      this.searchData.boxSize = "**";
      this.searchData.isOnFile = 0;
      this.searchData.unitSystem = this.unitsFlag;
      this.searchData.startTime = null;
      this.searchData.endTime = null;
      this.searchData.chineseName = null;
      this.searchData.sku = null;
      this.searchData.productTag = null;
      this.searchData.platformClassify = null;
      this.dateTime = [];
      this.getTableData();
    },
    //批量导入模态框
    SkuIncShowModel() {
      setTimeout(() => {
        this.$bus.$emit("SkuIncShowModel");
      }, 10);
    },
    //单位转换
    handleMenuClick(e) {
      this.searchData.unitSystem = e.key;
      this.unitsFlag = e.key;
      if (e.key === "0") {
        this.units = "重量：";
        this.unitsSize = "长(cm)*宽(cm)*高(cm)";
        this.unitFlag = "重量(g)";
        this.getTableData();
      } else if (e.key === "1") {
        this.units = "lb：";
        this.unitsSize = "in*in*in";
        this.unitFlag = "重量(lb)";
        this.getTableData();
      } else if (e.key === "2") {
        this.units = "oz：";
        this.unitsSize = "ft*ft*ft";
        this.unitFlag = "重量(oz)";
        this.getTableData();
      }
    },
    // //批量导入模板
    // async SKUUpDow() {
    // let res = await SKU_upDow();
    // console.log(res);
    // const blob = new Blob([res], {
    //   type: "application/vnd.ms-excel"
    // });
    // const fileName = "SKU列表.xlsx";
    // const linkNode = document.createElement("a");
    // linkNode.download = fileName; //a标签的download属性规定下载文件的名称
    // linkNode.style.display = "none";
    // linkNode.href = URL.createObjectURL(blob); //生成一个Blob URL
    // document.body.appendChild(linkNode);
    // linkNode.click(); //模拟在按钮上的一次鼠标单击
    // URL.revokeObjectURL(linkNode.href); // 释放URL 对象
    // document.body.removeChild(linkNode);
    // },
    //查询按钮
    searchBtn() {
      this.searchData.isOnFile = 0;
      this.getTableData();
    },

    //搜索日期选择器
    DateChange(date, dateString) {
      date;
      if (dateString && dateString.length > 0) {
        this.searchData.startTime = dateString[0];
        this.searchData.endTime = dateString[1];
      } else {
        this.searchData.startTime = "";
        this.searchData.endTime = "";
      }
      this.getTableData();
    },
    //获取批量分类数据
    async getBatchSKUTypeTree() {
      let { code, responseBody } = await SKU_TypeTree({
        tagType: 1,
        isDisable: 0,
        isChild: true,
      });
      if (code === "200") {
        this.platformOptions = req.treeDatas(responseBody);
      }
      let res = await SKU_TypeTree({
        tagType: 2,
        isDisable: 0,
        isChild: true,
      });
      if (res.code === "200") {
        this.freedomOptions = req.treeDatas(res.responseBody);
      }
    },
    //分页器事件
    onChangePage(pageNumber) {
      this.searchData.current = pageNumber;
      this.getTableData();
    },
    //页码变更
    showChange(size, current) {
      this.searchData.current = size;
      this.searchData.size = current;
      this.getTableData();
    },
    //新建SKU
    addNewSKU() {
      setTimeout(() => {
        this.$bus.$emit("showModel");
      }, 1);
    },
    //点击编辑
    eidtRow(e, row, flag) {
      setTimeout(async () => {
        if (flag === "edit") {
          this.$bus.$emit("skuListRowData", row, "edit");
        } else if (flag === "info") {
          this.$bus.$emit("skuListRowData", row, "info");
        } else if (flag === "download") {
          if (e.key === "1") {
            setTimeout(() => {
              this.$bus.$emit("SkuListTags", row);
            }, 10);
          } else if (e.key === "0") {
            let res = await SKU_PDF6030(
              `top=${row.productTag}&&bottom=${row.sku}`
            );
            req.exportPDF("60*30mm", res);
          } else if (e.key === "3") {
            let res = await SKU_PDFA4(
              `top=${row.productTag}&&bottom=${row.sku}`
            );
            req.exportPDF("letter", res);
          } else if (e.key === "4") {
            let res = await SKU_PDFA4(
              `top=${row.productTag}&&bottom=${row.sku}`
            );
            req.exportPDF("A4", res);
          }
        }
      });
    },
    //平台分类改变
    onPlatformOptionsChange(value) {
      this.platformArray = value;
    },
    //自由分类改变
    onFreedomOptionsChange(value) {
      this.freedomArray = value;
    },
    //搜索框过滤搜索
    filter(inputValue, path) {
      return path.some(
        (option) =>
          option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
      );
    },
    //已归档查询
    isOnFile() {
      this.searchData.isOnFile = 1;
      this.getTableData();
    },
    //批量删除
    showConfirm() {
      let _this = this;
      if (this.tablecheckedArray.length <= 0) {
        this.$message.error("请勾选需要删除的数据！");
        return false;
      } else {
        this.$confirm({
          title: "你确定要删除这些数据吗?",
          cancelText: "取消",
          okText: "确定",
          async onOk() {
            return new Promise((resolve) => {
              setTimeout(async () => {
                let { code, responseBody } = await SKU_batchDelete(
                  _this.tablecheckedArray
                );
                if (code === "200") {
                  resolve();
                  _this.$message.warning(responseBody);
                }
              }, 1000);
            }).then(() => {
              _this.getTableData(0);
              _this.tablecheckedArray = [];
            });
          },
          onCancel() {},
        });
      }
    },
    //批量归档
    async batchIsOnFile() {
      if (this.tablecheckedArray.length <= 0) {
        this.$message.error("请勾选需要归档得数据！");
        return false;
      }
      let { code } = await SKU_batchIsOnFile(this.tablecheckedArray);
      if (code === "10000") {
        this.getTableData();
        this.tablecheckedArray = [];
      }
    },
    // 表格checked框
    onSelectChange(selectedRowKeys) {
      this.tablecheckedArray = [];
      selectedRowKeys.forEach((item) => {
        this.tabledata.forEach((v) => {
          if (item === v.key) {
            this.tablecheckedArray.push({
              key: v.key,
              revision: v.revision,
            });
          }
        });
      });
      this.selectedRowKeys = selectedRowKeys;
    },
    async getTableData() {
      this.spinning = true;
      let searchDatas = { ...this.searchData };
      if (searchDatas.boxSize.length >= 3) {
        searchDatas.long = searchDatas.boxSize.split("*")[0];
        searchDatas.width = searchDatas.boxSize.split("*")[1];
        searchDatas.height = searchDatas.boxSize.split("*")[2];
      }
      searchDatas.current = this.searchData.current;
      searchDatas.size = this.searchData.size;
      searchDatas.startTime = searchDatas.startTime
        ? this.searchData.startTime + ` 00:00:00`
        : "";
      searchDatas.endTime = searchDatas.endTime
        ? this.searchData.endTime + ` 23:59:59`
        : "";
      let { code, responseBody } = await SKU_TableList(searchDatas);
      if (code === "200") {
        let { records } = responseBody;
        this.searchData.total = Number(responseBody.total);
        records.forEach((item) => {
          // item.serialNum = i + this.searchData.current * this.searchData.size - 9;
          item.boxSize = `${item.long}*${item.width}*${item.height}`;
          item.createTime = item.createTime.replace("T", "  ");
          item.updateTime = item.updateTime.replace("T", "  ");
        });
        this.tabledata = records;
        this.spinning = false;
      }
    },
  },
  computed: {
    columns() {
      return [
        {
          title: "产品分类",
          dataIndex: "platformClassifyName",
          align: "center",
          scopedSlots: { customRender: "platformClassifyName" },
          ellipsis: true,
          width: "7%",
        },
        // {
        //   title: "自有分类",
        //   dataIndex: "selfClassifyName",
        //   align: "center",
        //   scopedSlots: { customRender: "selfClassifyName" },
        //   ellipsis: true,
        //   width: "7%",
        // },
        {
          title: "产品SKU",
          dataIndex: "sku",
          align: "center",
          ellipsis: true,
          width: "9%",
          // scopedSlots: { customRender: "sku" },
        },
        {
          title: "产品标签",
          dataIndex: "productTag",
          ellipsis: true,
          // scopedSlots: { customRender: "productTag" },
          align: "center",
          width: "9%",
        },
        {
          title: "产品名称",
          dataIndex: "chineseName",
          ellipsis: true,
          // scopedSlots: { customRender: "chineseName" },
          align: "center",
          width: "9%",
        },
        {
          title: this.unitsSize,
          dataIndex: "boxSize",
          // scopedSlots: { customRender: "boxSize" },
          align: "center",
          ellipsis: true,
          width: "11%",
        },
        {
          title: "重量",
          dataIndex: "weight",
          scopedSlots: { customRender: "weightUnit" },
          align: "center",
          ellipsis: true,
          width: "7%",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          scopedSlots: { customRender: "createTime" },
          align: "center",
          width: "12%",
        },
        {
          title: "更新时间",
          dataIndex: "updateTime",
          scopedSlots: { customRender: "updateTime" },
          align: "center",
          width: "12%",
        },
        {
          title: "备注",
          dataIndex: "remarks",
          scopedSlots: { customRender: "remarks" },
          align: "center",
          ellipsis: true,
          width: "9%",
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: 150,
          fixed: "right",
        },
      ];
    },
  },
};
</script>

<style lang="less" scoped>
#components-form-demo-advanced-search {
  padding: 5px;
  input {
    width: 60%;
  }
}
.top-btn {
  background: #fff;
  color: #3eae7c;
  text-shadow: none;
}
.top-btn:hover {
  background: #3eae7c;
  color: #fff;
}
.action {
  a {
    border-bottom: 1px solid rgb(41, 41, 224);
    color: rgb(41, 41, 224);
  }
}
</style>
